// packageC/pages/package/OCR_namage/index.js
const mybehavior = require("../../../../behaviors/requests")
Page({

  /**
   * 页面的初始数据
   */
  behaviors: [mybehavior],
  data: {
    baseUrl: "https://logisticsengineering.gree.com/ocr_calling_api/gaolan_ocr_bp",
    data_list: [

    ],
    uid: "",
    caozuo_show: false,
    row_data: {}
  },
  //   查看详情
  showDetail(e) {
    // console.log(e.currentTarget.dataset.row);
    let row = e.currentTarget.dataset.row_data
    wx.navigateTo({
      url: '/packageC/pages/package/OCR_namage/detail/index',
      success(res) {
        res.eventChannel.emit('showDetail', row)
      }
    })

  },
  // 扫描输入值
  scan() {
    const self = this;
    wx.scanCode().then((res) => {
      const label_code = res.result;
      wx.showLoading({
        title: "loading"
      })
      console.log(label_code);
      setTimeout(function () {
        wx.hideLoading()
        self.setData({
          uid: label_code,
        })
        self.getDeviceData()
      }, 500)
    }).catch(err => {
      wx.hideLoading()
      console.log(err);
    });
  },
  caozuoBtn(e) {
    console.log(e);
    let row = e.currentTarget.dataset.row_data
    this.setData({
      caozuo_show: true,
      row_data: row
    })
  },
  onCzCancel() {
    this.setData({
      caozuo_show: false,
      row_data: {}
    })
  },
  // 重置查询条件
  resetSearchData() {
    this.setData({
      uid: "",
    })
    this.newPromiseGetValue()
  },


  getDatas(resolve, reject) {
    let url = this.data.baseUrl + "/query_devices";
    let data = {
      uid: this.data.uid,
      address: "",
      description: "",
      page: 1,
      page_size: 9999,
    }
    this.post(url, data).then(res => {
      // console.log("返回list结果", res)
      if (res.code == 20000) {
        let res_arr = res.data.results
        for (let i = 0; i < res_arr.length; i++) {
          const reboot_copied_time1 = this.GMTToStr(res_arr[i].reboot_copied_time)
          for (let j = 0; j < res_arr[i].params.length; j++) {
            res_arr[i].params[j].reboot_copied_time = reboot_copied_time1
          }
        }
        // wx.showToast({
        //   title: res.msg,
        //   icon: "success"
        // });
        wx.hideLoading()
        resolve(res_arr)
      } else {
        this.setData({
          data_list: []
        })
        wx.showToast({
          title: res.msg,
          icon: "error"
        })
        reject()
      }
    }).catch(err => {
      wx.hideLoading()
      this.setData({
        data_list: []
      })
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
      reject()
    })
  },

  // 查询-光电设备--集合
  getGPIOData1(e, resolve, reject) {

    let url = this.data.baseUrl + "/query_gpio";

    for (let i = 0; i < e.length; i++) {
      let uid = e[i]._id
      let data = {
        uid: uid,
        page: 1,
        page_size: 1,
      }
      this.post(url, data).then(res => {
        if (res.code == 20000) {
          let res_arr = res.data.results
          for (let j = 0; j < res_arr.length; j++) {
            res_arr[j].report_time = this.GMTToStr(res_arr[j].report_time)
          }
          e[i].gpio_data = res_arr
          resolve(e)
        } else {
          e[i].gpio_data = []
          reject(e)
        }

      }).catch(err => {
        e[i].gpio_data = []
        reject(e)
      })

    }




  },


  newPromiseGetValue() {
    new Promise((resolve, reject) => {
      this.getDatas(resolve, reject)
    }).then(res => {
      new Promise((resolve1, reject1) => {
        console.log("第一步", res);
        this.getGPIOData1(res, resolve1, reject1)
      }).then(res1 => {
        console.log("第二步", res1);
        this.searchHouseStatus(res1)
      }).catch(err1 => {
        console.log("第二步", err1);
        console.log("err1", err1);
        this.searchHouseStatus(err1)
      })
    }).catch(err => {
      console.log("err", err);

    })
  },



  // 查询-OCR设备--集合
  getDeviceData() {
    wx.showLoading({
      title: '加载中...',
    })
    let url = this.data.baseUrl + "/query_devices";
    let data = {
      uid: this.data.uid,
      address: "",
      description: "",
      page: 1,
      page_size: 9999,
    }


    this.post(url, data).then(res => {
      // console.log("返回list结果", res)
      if (res.code == 20000) {
        let res_arr = res.data.results
        for (let i = 0; i < res_arr.length; i++) {
          const reboot_copied_time1 = this.GMTToStr(res_arr[i].reboot_copied_time)
          for (let j = 0; j < res_arr[i].params.length; j++) {
            res_arr[i].params[j].reboot_copied_time = reboot_copied_time1
          }

        }
        setTimeout(() => {
          this.getGPIOData(res_arr)
        }, 300)


        // wx.showToast({
        //   title: res.msg,
        //   icon: "success"
        // });
        wx.hideLoading()
      } else {
        this.setData({
          data_list: []
        })
        wx.showToast({
          title: res.msg,
          icon: "error"
        })
      }
    }).catch(err => {
      wx.hideLoading()
      this.setData({
        data_list: []
      })
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  // 查询-光电设备--集合
  getGPIOData(e) {

    let url = this.data.baseUrl + "/query_gpio";

    for (let i = 0; i < e.length; i++) {
      let uid = e[i]._id
      let data = {
        uid: uid,
        page: 1,
        page_size: 1,
      }
      this.post(url, data).then(res => {
        if (res.code == 20000) {
          let res_arr = res.data.results
          for (let j = 0; j < res_arr.length; j++) {
            res_arr[j].report_time = this.GMTToStr(res_arr[j].report_time)
          }
          e[i].gpio_data = res_arr
        }
      }).catch(err => {
        e[i].gpio_data = []

      })

    }
    setTimeout(() => {
      this.searchHouseStatus(e)
    }, 1000)



  },
  // 查询-原始图片--集合
  searchImg() {
    this.setData({
      caozuo_show: false
    })
    let row = this.data.row_data
    wx.showLoading({
      title: '处理中...',
    })
    let url = this.data.baseUrl + "/query_origin_frames";
    let data = {
      uid: row._id,
      page: 1,
      page_size: 1,
    }

    this.post(url, data).then(res => {
      console.log("返回结果", res)
      if (res.code == 20000) {
        wx.hideLoading()
        let val = res.data.results[0]
        wx.navigateTo({
          url: '/packageC/pages/package/OCR_namage/show_img/index',
          success(res) {
            res.eventChannel.emit('showOriginImg', val)
          }
        })
      } else {

        wx.showToast({
          title: res.msg,
          icon: "error"
        })
      }
    }).catch(err => {
      wx.hideLoading()
      // this.setData({
      //   data_list: []
      // })
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  // 查询-库位状态--集合
  searchHouseStatus(e) {
    console.log("xasdasd", e);
    this.setData({
      caozuo_show: false
    })
    wx.showLoading({
      title: '处理中...',
    })
    let row = e
    let url = this.data.baseUrl + "/query_points";
    for (let i = 0; i < row.length; i++) {

      let data = {
        uid: row[i]._id,
        page: 1,
        page_size: 1,
      }
      this.post(url, data).then(res => {

        // console.log("当前设备list:", row[i]);
        // console.log("返回point结果", res)
        if (res.code == 20000) {
          let val = res.data.results[0]
          let als_list = val.als
          console.log("库位数组：", als_list);
          let show_list = []
          for (let j = 0; j < als_list.length; j++) {
            let obj = {
              name: row[i].params[j].al,
              status: val.als[j],
              time: this.GMTToStr(val.report_time),
              points: val.points[j],
              uid: row[i]._id,
              index: j
            }
            show_list.push(obj)
          }


          row[i].show_list = show_list
          this.setData({
            data_list: row
          })
          wx.showToast({
            title: "成功",
            icon: "none"
          });
          wx.hideLoading()
        } else {

          // wx.showToast({
          //   title: res.msg,
          //   icon: "error"
          // })
        }
      }).catch(err => {
        wx.hideLoading()
        this.setData({
          data_list: row
        })
        // wx.showToast({
        //   title: err.msg,
        //   icon: 'none'
        // })
      })
    }


  },
  // 跳转操作界面
  setBtn(e) {
    let row = this.data.row_data
    let flag = e.currentTarget.dataset.type
    console.log(flag);
    if (flag == 'mode') {
      wx.navigateTo({
        url: '/packageC/pages/package/OCR_namage/edit/index',
        success(res) {
          res.eventChannel.emit('setMode', row)
        }
      })
    }
    if (flag == 'rate') {
      wx.navigateTo({
        url: '/packageC/pages/package/OCR_namage/edit/index',
        success(res) {
          res.eventChannel.emit('setRate', row)
        }
      })
    }
    if (flag == 'address') {
      wx.navigateTo({
        url: '/packageC/pages/package/OCR_namage/edit/index',
        success(res) {
          res.eventChannel.emit('setAddress', row)
        }
      })
    }
    if (flag == 'description') {
      wx.navigateTo({
        url: '/packageC/pages/package/OCR_namage/edit/index',
        success(res) {
          res.eventChannel.emit('setDescription', row)
        }
      })
    }
    if (flag == 'admin') {
      wx.navigateTo({
        url: '/packageC/pages/package/OCR_namage/edit/index',
        success(res) {
          res.eventChannel.emit('setAdmin', row)
        }
      })
    }
    if (flag == 'params') {
      wx.navigateTo({
        url: '/packageC/pages/package/OCR_namage/edit/index',
        success(res) {
          res.eventChannel.emit('setParams', row)
        }
      })
    }

    this.setData({
      caozuo_show: false,
      row_data: {}
    })
  },
  toShowImg(e) {
    let row = e.currentTarget.dataset.row
    wx.navigateTo({
      url: '/packageC/pages/package/OCR_namage/show_img/index',
      success(res) {
        res.eventChannel.emit('showPointImg', row)
      }
    })
  },
  // 重启设备
  resetDevice() {
    wx.showModal({
      title: '确认重启该设备?',
      complete: (res) => {
        if (res.cancel) {

        }

        if (res.confirm) {
          wx.showLoading({
            title: '处理中...',
          })
          let url = this.data.baseUrl + "/reboot_device";
          let data = {
            uid: this.data.row_data._id,
          }
          this.post(url, data).then(res => {
            console.log("返回结果", res)
            if (res.code == 20000) {
              setTimeout(() => {
                this.getDeviceData()
              }, 500)
              wx.showToast({
                title: res.msg,
                icon: "success"
              });

            } else {
              wx.showToast({
                title: res.msg,
                icon: "error"
              })
            }
          }).catch(err => {

            wx.hideLoading()
            wx.showToast({
              title: err.msg,
              icon: 'none'
            })
          })

        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.newPromiseGetValue()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成 
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})